package puzzle.common.imgreader;

import java.awt.image.BufferedImage;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import javax.imageio.ImageIO;

import tomoto.util.IntVectorUtil;

public class ImgPatternFactory {
	public static ImgPattern createFromImages(Iterator<InputStream> iss, double matchFactor,
			int priority) throws IOException {
		List<ImgPattern> patterns = new ArrayList<ImgPattern>();
		while (iss.hasNext()) {
			InputStream is = iss.next();
			ImgPattern pattern = createFromImage(is, matchFactor, priority);
			is.close();
			patterns.add(pattern);
		}

		int count = patterns.size();

		if (count == 0) {
			return null;
		}

		int w = patterns.get(0).width;
		int h = patterns.get(0).height;

		int[] pixels = new int[w * h];
		for (ImgPattern pattern : patterns) {
			assert pattern.width == w && pattern.height == h;
			IntVectorUtil.add(pixels, pattern.pixels);
		}
		IntVectorUtil.div(pixels, count);

		return new ImgPattern(w, h, pixels, matchFactor, priority);
	}

	public static ImgPattern createFromImage(InputStream is, double matchFactor, int priority)
			throws IOException {
		BufferedImage img = (BufferedImage) ImageIO.read(is);
		int w = img.getWidth();
		int h = img.getHeight();
		int[] pixels = img.getRGB(0, 0, w, h, null, 0, w);

		IntVectorUtil.logand(pixels, 0xff); // the image should be gray scale

		return new ImgPattern(w, h, pixels, matchFactor, priority);
	}

}
